<template>
  <!-- 员工页面 -->
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>

      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" sortable="">
            <template #default="{$index}">
              {{ (page.page-1)*page.size+$index+1 }}
            </template>
          </el-table-column>
          <el-table-column label="头像" sortable="" prop="username" width="120">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/bigUserHeader.png')" :src="row.staffPhoto" alt="" class="imgUrl" @click="showImg(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formOfEmploymentMatter" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry|formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <el-switch
                :value="row.enableState===1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="roleFn(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPerm('delRole')" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page.page"
            :page-sizes="[1, 2, 5, 8]"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 新增表单 -->
    <addEmployees :show-dialog.sync="showDialog" />
    <!-- 二维码弹窗 -->
    <el-dialog :visible.sync="isshowImg" title="头像二维码">
      <el-row type="flex" justify="center">
        <canvas ref="canvasRef" />
      </el-row>
    </el-dialog>

    <!-- 角色权限弹窗 -->
    <assignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import assignRole from './components/assign-role.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import { formatDate } from '@/filters'
import addEmployees from './components/add_employees.vue'
// import PageTools from '@/components/PageTools/index.vue'
import QRCode from 'qrcode'
export default {
  components: {
    // PageTools
    addEmployees,
    assignRole
  },
  data() {
    return {
      showDialog: false,
      list: [], // 员工列表数据
      page: {
        page: 1,
        size: 2
      },
      total: 0,
      loading: false,
      isshowImg: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // checkPerm(pointName) {
    //   return this.$store.state.user.userInfo.roles.points.includes(pointName)
    // },
    // 员工列表数据
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows.map(item => ({ ...item, enableState: item.enableState || 1 }))
      this.total = total
      this.loading = false
      console.log(this.list)
    },
    // 页面改变
    handleSizeChange(val) {
      this.page.size = val
      this.getEmployeeList()
    },
    // 页面条数改变
    handleCurrentChange(val) {
      this.page.page = val
      this.getEmployeeList()
    },
    // 聘用形式的格式
    // cell格子的数据
    formOfEmploymentMatter(row, col, cell, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cell)
      return obj ? obj.value : '未知形式'
    },
    // 导出功能
    async  exportExcel() {
      // console.log(1)
      // 拿到所有的数据
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      // console.log(res)
      // 转换字典
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 头部
      const header = Object.keys(dict)
      console.log(header)
      // 数据的转换
      const newData = rows.map(item => {
        return this.obj2Arr(item, dict)
      })
      console.log(newData)
      // 按需导入
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      // console.log(export_json_to_excel)
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '性别'],
      //   data: [
      //     ['小明', 3, '男'],
      //     ['小红', 4, '女'],
      //     ['小刚', 6, '男']
      //   ]
      // })
      export_json_to_excel({
        header,
        data: newData
      })
    },
    // 对象转换为数组
    // 我们还有字典, 字典是用来确定顺序的
    // 只需要按顺序遍历字典, 每个key 都去拿 value 放入数组
    obj2Arr(user, dict) {
      const res = []
      // for (const key in dict) {
      //   const enKey = dict[key] // 英文的key
      //   let value = user[enKey]
      //   // console.log(enKey)
      //   // console.log(value)
      //   // 如果有枚举数据
      //   if (enKey === 'formOfEmployment') {
      //     const obj = EmployeeEnum.hireType.find(item => item.id === value)
      //     value = obj ? obj.value : '未知形式'
      //   }
      //   // 如果是时间
      //   if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
      //     value = formatDate(value)
      //   }

      //   res.push(value)
      // }

      // 第二种
      Object.keys(dict).forEach(key => {
        const enKey = dict[key]// 英文的key
        // value为每一个的值
        let value = user[enKey]
        // console.log(enKey)
        if (enKey === 'formOfEmployment') {
          const obj = EmployeeEnum.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知形式'
        }
        // 如果是时间
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          value = formatDate(value)
        }

        res.push(value)
      })

      return res
    },
    // 删除角色
    async  delEmployee(id) {
      const del = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (del === 'cancel') return this.$message.info('用户取消删除')
      await delEmployee(id)
      this.$message.success('用户删除成功')
      if (this.list.length === 1 && this.page.page > 1) {
        this.page.page--
      }
      this.getEmployeeList()
    },
    showImg(imgsrc) {
      if (imgsrc) {
        this.isshowImg = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.canvasRef, imgsrc, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    // 点击角色
    async  roleFn(id) {
      await this.$refs.assignRole.getUserDetail(id)
      // 保存用户id
      this.userId = id
      this.showRoleDialog = true
    }

  }
}
</script>

<style lang="scss" scoped>
.imgUrl{
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 50%;
}
</style>
